import 'package:state_management_redux/contactor/contactor_state.dart';

import 'contactor_action.dart';

ContactorState contactorReducer(ContactorState state, dynamic action) {
  if (action is RefreshAction) {
    ContactorState contactorState = ContactorState(state.contactors,
        isLoading: true, errorMessage: null, currentPage: 1);
    return contactorState;
  }
  if (action is LoadAction) {
    ContactorState contactorState = ContactorState(state.contactors,
        isLoading: true,
        errorMessage: null,
        currentPage: state.currentPage + 1);
    return contactorState;
  }

  if (action is SuccessAction) {
    int currentPage = action.currentPage;
    List<dynamic> contactors = state.contactors;
    if (currentPage > 1) {
      contactors += action.jsonItems;
    } else {
      contactors = action.jsonItems;
    }
    ContactorState contactorState = ContactorState(contactors,
        isLoading: false, errorMessage: null, currentPage: currentPage);
    return contactorState;
  }

  if (action is FailedAction) {
    ContactorState contactorState = ContactorState(
      state.contactors,
      isLoading: false,
      errorMessage: action.errorMessage,
    );
    return contactorState;
  }

  return state;
}
